package com.joejag.mavenstats.server.xml;

import com.joejag.mavenstats.client.dto.DependencyDTO;
import nu.xom.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MavenProjectReader
{
   private String projectURL;

   public MavenProjectReader(String projectURL)
   {
      this.projectURL = projectURL;
   }

   public List<DependencyDTO> getDependencies()
   {
      Document doc = getDocument();
      List<DependencyDTO> result = new ArrayList();

      Nodes nodes = doc.query("/project/dependencies/dependency");
      for (int i = 0; i < nodes.size(); i++)
      {
         Node node = nodes.get(i);

         String grouping = getChildElementValue(node, "groupId");
         String name = getChildElementValue(node, "artifactId");

         if (grouping.length() == 0)
         {
            grouping = getChildElementValue(node, "id");
            name = grouping;
         }

         String version = getChildElementValue(node, "version");
         result.add(new DependencyDTO(grouping, name, version));
      }
      return result;
   }

   private Document getDocument()
   {
      try
      {
         Builder parser = new Builder();
         Document doc = parser.build(projectURL);
         return doc;
      } catch (ParsingException ex)
      {
         System.out.println(projectURL + " is not well-formed.");
         System.out.println(ex.getMessage());
      }
      catch (IOException ex)
      {
         System.out.println("Due to an IOException, the parser could not print " + projectURL);
      }

      throw new RuntimeException("Cannot parse document " + projectURL);
   }

   private String getChildElementValue(Node node, String childName)
   {
      Element childElement = ((Element) node).getFirstChildElement(childName);
      return childElement == null ? "" : childElement.getValue();
   }

   public String getProjectName()
   {
      Document document = getDocument();
      Nodes nodes = document.query("/project/name");
      if (nodes.size() == 0)
         return "";

      return nodes.get(0).getValue();
   }
}
